package com.xdf.docmanagementsystem.controller;

import com.xdf.docmanagementsystem.common.base.BaseController;
import com.xdf.docmanagementsystem.common.util.IOUtil;
import com.xdf.docmanagementsystem.common.util.ObjectUtil;
import com.xdf.docmanagementsystem.entity.DocExtraFile;
import com.xdf.docmanagementsystem.entity.DocumentDailyRecord;
import com.xdf.docmanagementsystem.enums.OperatorEnum;
import com.xdf.docmanagementsystem.enums.PathEnum;
import com.xdf.docmanagementsystem.enums.ResponseEnum;
import com.xdf.docmanagementsystem.service.DocExtraFileService;
import com.xdf.docmanagementsystem.service.DocumentDailyRecordService;
import com.xdf.docmanagementsystem.vo.DocExtraFileVo;
import com.xdf.docmanagementsystem.vo.DocumentModelVo;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.xdf.docmanagementsystem.entity.ResponseResult;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.xdf.docmanagementsystem.entity.Document;
import com.xdf.docmanagementsystem.service.DocumentService;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description : 自动生成的控制层
 * @Author : ZK
 * @Date : 2020-06-21 12:45:28
 */
@Api(tags = "文档档案")
@CrossOrigin
@RestController
@RequiresUser
@RequestMapping("/document")
public class DocumentController extends BaseController {
    private static final Mapper mapper = new DozerBeanMapper();

    @Autowired
    private DocumentService service;
    @Autowired
    private DocExtraFileService docExtraFileService;
    @Autowired
    private DocumentDailyRecordService dailyRecordService;

    /**
     * @Description : 选择新增
     * @Return : ResponseResult<Void>
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "选择新增", httpMethod = "POST", notes = "自动生成的新增方法")
    @RequestMapping(value = "/insertSelective", method = RequestMethod.POST)
    public ResponseResult<Void> insertSelective(Document record) throws Exception {
        service.insertSelective(record);
        return new ResponseResult<Void>();
    }

    /**
     * @Description : 批量新增
     * @Return : ResponseResult<Void>
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "批量新增", httpMethod = "POST", notes = "自动生成的新增方法")
    @RequestMapping(value = "/multiInsert", method = RequestMethod.POST)
    public ResponseResult<Void> multiInsert(@RequestBody List<Document> list) throws Exception {
        service.multiInsert(list);
        return new ResponseResult<Void>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage());
    }

    /**
     * @Description : 选择修改
     * @Return : Document
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "选择修改", httpMethod = "PUT", notes = "自动生成的修改方法")
    @RequestMapping(value = "/updateSelective", method = RequestMethod.POST)
    public ResponseResult<Void> updateSelective(Document record) throws Exception {
        service.updateByPrimaryKeySelective(record);
        return new ResponseResult<Void>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage());
    }

    /**
     * @Description : 批量修改
     * @Return : Document
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "批量修改", httpMethod = "POST", notes = "自动生成的修改方法")
    @RequestMapping(value = "/multiUpdate", method = RequestMethod.POST)
    public ResponseResult<Void> multiUpdate(@RequestBody List<Document> list) throws Exception {
        Assert.state(list != null && list.size() > 0, ResponseEnum.NOT_ALLOW.getMessage());
        for (Document document : list) {
            Document item = service.selectByPrimaryKey(document.getId());
            Assert.notNull(item, ResponseEnum.NOT_EXIST.getMessage());
            // Assert.state(item.getDocStatus() > 1, "编号:" + item.getEmpNumber() + "已清空!");
            service.updateByPrimaryKeySelective(document);
        }
        return new ResponseResult<Void>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage());
    }

    /**
     * @Description : 根据主键查询
     * @Return : Document
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "根据主键查询", httpMethod = "GET", notes = "自动生成的查询方法")
    @RequestMapping(value = "/queryByPk/{id}", method = RequestMethod.GET)
    public DocumentModelVo selectByPrimaryKey(@PathVariable("id") Integer id) throws Exception {
        if (id == null) return null;
        DocumentModelVo documentModelVo = mapper.map(service.selectByPrimaryKey(id), DocumentModelVo.class);
        documentModelVo.setDetail(ObjectUtil.conventList(mapper, docExtraFileService.listQuery(DocExtraFile.builder().documentId(id).fileStatus(1).build()), DocExtraFileVo.class));
        return documentModelVo;
    }

    /**
     * @Description : 查询方法
     * @Return : java.util.List
     * @Author : ZK
     * @Date : 2020-06-21 12:45:28
     */
    @ApiOperation(value = "查询方法", httpMethod = "GET", notes = "自动生成的查询方法")
    @RequestMapping(value = "/listQuery", method = RequestMethod.GET)
    public List<Document> query(Document record) throws Exception {
        return service.listQuery(record);
    }

    /**
     * 根据主键作废
     *
     * @param id
     * @return
     * @throws Exception
     */
    @PostMapping("/cancel")
    public ResponseResult<Void> cancelByDocumentId(Integer id) throws Exception {
        Assert.notNull(service.selectByPrimaryKey(id), ResponseEnum.ALREADY_DELETE.getMessage());
        Assert.state(service.updateByPrimaryKeySelective(Document.builder().id(id).docStatus(0).build()) > 0, ResponseEnum.ERROR_DELETE.getMessage());
        return new ResponseResult<Void>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage());
    }

    /**
     * 根据主键查询
     *
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/queryById/{id}")
    @ApiOperation(value = "根据主键查询")
    public DocumentModelVo queryById(@PathVariable("id") Integer id) throws Exception {
        Document doc = service.selectByPrimaryKey(id);
        if (doc == null) return null;
        List<DocExtraFile> docExtraFiles = docExtraFileService.listQuery(DocExtraFile.builder().documentId(id).fileStatus(1).build());
        DocumentModelVo documentModelVo = mapper.map(doc, DocumentModelVo.class);
//        documentModelVo.setDocExtraFiles(ObjectUtil.conventList(mapper, docExtraFiles, DocExtraFileVo.class));
        return documentModelVo;
    }

    /**
     * 查询报表
     *
     * @param departmentId
     * @param status
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "报表")
    @RequestMapping(value = "/report", method = RequestMethod.GET)
    public List<Map<String, Object>> report(
            @RequestParam(value = "departmentId", required = false) Integer departmentId,
            @RequestParam(value = "status", required = false, defaultValue = "1") Integer status) throws Exception {
        return service.report(departmentId, status);
    }

    /**
     * 文件上传
     *
     * @param fileUpload
     * @return
     * @throws Exception
     */
    @PostMapping("/upload/batch")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<DocumentModelVo> uploadFiles(DocumentModelVo fileUpload) throws Exception {
        Document doc = mapper.map(fileUpload, Document.class);
        Assert.state(service.insertSelective(doc) > 0, ResponseEnum.ERROR_ADD.getMessage());
        String savePath = new StringBuilder()
                .append(PathEnum.SAVE_PATH.getPath())
                .append(File.separator)
                .append(PathEnum.DOC_SUB_PATH.getPath())
                .append(File.separator)
                .append(doc.getId()).toString();
        String path = new StringBuilder()
                .append(System.getProperty("user.dir"))
                .append(File.separator)
                .append(savePath)
                .toString();

        // 日志记录
        DocumentDailyRecord documentDailyRecord = mapper.map(doc, DocumentDailyRecord.class);
        if (documentDailyRecord != null) {
            documentDailyRecord.setModifyOperate(OperatorEnum.ADD.getOperatorName());
            dailyRecordService.insertSelective(documentDailyRecord);
        }

        List<MultipartFile> multipartFiles = fileUpload.getFiles();
        //  删除文件
        IOUtil.deleteFilesInDir(path);
        writeFiles(multipartFiles, path);
        return new ResponseResult<DocumentModelVo>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage(), mapper.map(doc, DocumentModelVo.class));
    }

    /**
     * 修改
     *
     * @param documentModelVo
     * @return
     */
    @PostMapping("/upload/update")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<DocumentModelVo> update(DocumentModelVo documentModelVo) throws Exception {
        Document doc = mapper.map(documentModelVo, Document.class);
        Assert.state(doc.getId() != null, ResponseEnum.NOT_ALLOW.getMessage());
        service.updateByPrimaryKeySelective(doc);

        // 日志记录
        DocumentDailyRecord documentDailyRecord = mapper.map(doc, DocumentDailyRecord.class);
        if (documentDailyRecord != null) {
            documentDailyRecord.setModifyOperate(OperatorEnum.MODIFY.getOperatorName());
            dailyRecordService.insertSelective(documentDailyRecord);
        }

        String savePath = new StringBuilder()
                .append(PathEnum.SAVE_PATH.getPath())
                .append(File.separator)
                .append(PathEnum.DOC_SUB_PATH.getPath())
                .append(File.separator)
                .append(doc.getId()).toString();
        String path = new StringBuilder()
                .append(System.getProperty("user.dir"))
                .append(File.separator)
                .append(savePath)
                .toString();

        List<MultipartFile> multipartFiles = documentModelVo.getFiles();
        writeFiles(multipartFiles, path);
        return new ResponseResult<DocumentModelVo>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage(), mapper.map(doc, DocumentModelVo.class));
    }

    /**
     * 根据Excel文件新增文档单据
     *
     * @param list
     * @return
     */
    @PostMapping("/upload/fromExcel")
    public ResponseResult<Void> insertByExcelFiles(List<MultipartFile> list) {
        return new ResponseResult<Void>(true, ResponseEnum.OK.getState(), ResponseEnum.OK.getMessage());
    }
}